package com.aco.fatureapp.activity;

import javax.inject.Inject;

import roboguice.inject.InjectView;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.aco.fatureapp.R;
import com.aco.fatureapp.model.AccessLog;
import com.aco.fatureapp.model.AccessLog.TypeAction;
import com.aco.fatureapp.model.Leiturista;
import com.aco.fatureapp.service.SrvAccess;
import com.aco.fatureapp.utilitary.Utils;
import com.mobsandgeeks.saripaar.annotation.Required;

public class AccessActivity extends BaseActivity {

	public static final String DATE_BUILD_VERSION = "dateBuildVersion";

	@InjectView(tag = "txtUser")
	@Required(order = 1, message = "Campo Obrigatório")
	private EditText mTxtUser;

	@InjectView(tag = "txtPassword")
	@Required(order = 2, message = "Campo Obrigatório")
	private EditText mTxtPassword;

	@InjectView(tag = "txtVersion")
	private TextView mTxtVersion;

	@InjectView(tag = "btnAccess")
	private Button mBtnAccess;

	@InjectView(tag = "txtConfiguracoes")
	private TextView mTxtConfiguracoes;

	@Inject
	private SrvAccess mSrvAccess;

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_access);

		// Becoming not cancelable.
		setFinishOnTouchOutside(false);

		registerBtnAccessOnClick();
		buildVersionName();

		mTxtConfiguracoes.setText(getStringResourceByName("configuracoes"));
		mTxtConfiguracoes.setAutoLinkMask(Linkify.ALL);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see roboguice.activity.RoboActivity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onRestart();
		mTxtPassword.setText(null);
	}

	/**
	 * Register event click for button access and validate inputs.
	 */
	private void registerBtnAccessOnClick() {
		mBtnAccess.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(final View v) {
				validator.validate();
			}
		});

		/**
		 * Chamar a tela de configurações.
		 */
		mTxtConfiguracoes.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent("IF_CONFIGURATION"));
			}
		});
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.aco.fatureapp.activity.BaseActivity#onValidationSucceeded()
	 */
	@Override
	public void onValidationSucceeded() {
		// Verificar se as configurações do App já foram criadas.
		new LoginAsyncTask().execute();

		// Leiturista findById = Leiturista.findById(Leiturista.class, 2L);
		// SrvAccess.login(getApplicationContext(), findById,
		// Leiturista.LEITURISTA);
		//
		// startActivity(new Intent("MAIN"));
	}

	/**
	 * Generate version name.
	 */
	private void buildVersionName() {
		try {
			final PackageInfo pinfo = getPackageManager().getPackageInfo(
					getPackageName(), 0);
			mTxtVersion.setText("Versão " + pinfo.versionName + " - "
					+ getStringResourceByName(DATE_BUILD_VERSION));
		}
		catch (final NameNotFoundException e) {
			mTxtVersion.setText("");
		}
	}

	private void goConfigurationHome(final AccessLog result) {
		Utils.alert(AccessActivity.this, result.getMessage(),
				new Dialog.OnClickListener() {

					@Override
					public void onClick(final DialogInterface dialog,
							final int which) {
						startActivity(new Intent("IF_CONFIGURATION"));
					}
				});
	}

	/**
	 * Tarefa responsável pela verificação da configuração do App, caso ainda
	 * não exista vai abrir a tela para gravação. Caso já tenha a configuração,
	 * validar o login para liberar o acesso ao sistema.
	 *
	 * @author aldivone
	 *
	 */
	public class LoginAsyncTask extends AsyncTask<Void, Void, AccessLog> {

		ProgressDialog mProgressDialog = null;

		/*
		 * (non-Javadoc)
		 *
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(AccessActivity.this);
			mProgressDialog.setCancelable(false);
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.setTitle("iFature Mobile");
			mProgressDialog.setMessage("Aguarde enquanto validamos"
					+ " suas credenciais de acesso.");

			mProgressDialog.show();
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see android.os.AsyncTask#doInBackground(java.lang.Object[])
		 */
		@Override
		protected AccessLog doInBackground(final Void... params) {
			try {
				AccessLog configurationOk = mSrvAccess.isConfigurationOk();

				if (configurationOk != null) {
					return configurationOk;
				}

				AccessLog validateLogin = mSrvAccess.validateLogin(mTxtUser
						.getText().toString(), mTxtPassword.getText()
						.toString(), Utils.getImei(getApplicationContext()));

				if (validateLogin != null
						&& TypeAction.LOGIN.equals(validateLogin
								.getTypeAction())) {
					// Gravar o usuário na sessão.
					SrvAccess.login(getApplicationContext(),
							validateLogin.getLeiturista(),
							Leiturista.LEITURISTA);
				}

				return validateLogin;
			}
			catch (final Exception ex) {
				return new AccessLog(TypeAction.ERROR, ex.getMessage());
			}
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(final AccessLog result) {
			mProgressDialog.dismiss();

			if (result != null) {
				switch (result.getTypeAction()) {
				case ERROR: {
					Utils.alert(AccessActivity.this, result.getMessage(), null);
					break;
				}
				case CONFIGURATION: {
					goConfigurationHome(result);
					break;
				}
				case LOGIN: {
					startActivity(new Intent("MAIN"));
					break;
				}
				}
			}
		}
	}
}
